package cn.song.interceptor;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import cn.song.common.R;
import cn.song.utils.HttpContextUtil;
import cn.song.utils.JavaWebToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Admin拦截器
 */
@Slf4j
public class MyAdminInterpcter implements HandlerInterceptor {


    @Autowired
    private JedisPool jedisPool;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Jedis jedis = jedisPool.getResource();
        try {
            //从请求头中获取token
            String token = request.getHeader("token");
            if (StringUtils.isBlank(token)) {
                token = request.getParameter("token");
            }
            System.err.println( "=============token========="+token);
            //判断token
            if (token != null && token.trim().length() > 10) {
                Map<String, Object> map = JavaWebToken.parserJavaWebToken(token);
                if (map != null) {

                    String bianma = map.get("bianma").toString();

                    if (!bianma.contains("YG")) {
                        setReturn(response, R.error(-150, "请使用员工账户登录"));
                        jedis.close();
                        return false;
                    }

                    String TOKEN = jedis.get(map.get("bianma").toString());
                    System.err.println(  "======================"+TOKEN);

                    if (map.get("bianma").toString() != null) {

                        if (TOKEN == null) {
                            jedis.close();
                            setReturn(response, R.error(-120, "未登录"));
                        } else if (TOKEN.equals(token)) {
                            jedis.setex(map.get("bianma").toString(), 60 * 60 * 2, token);
                            jedis.close();
                            PageHelper.clearPage();
                            return true;
                        } else {
                            jedis.close();
                            setReturn(response, R.error(-110, "登录超时"));
                        }
                    } else {
                        jedis.close();
                        setReturn(response, R.error(-140, "token中不包含bianma"));
                    }
                } else {
                    setReturn(response, R.error(-130, "无权限，请登录"));
                }

            } else {
                setReturn(response, R.error(-120, "未登录"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("错误", e);
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        PageHelper.clearPage();


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (ex instanceof Exception) {
            log.error("错误", ex);
            response.setCharacterEncoding("utf-8");
            setReturn(response,  R.error(-1000, "系统错误:" + ex.getMessage()));
        }

    }

    public static void setReturn(HttpServletResponse response, R r) throws IOException {
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
        //UTF-8编码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(JSON.toJSON(r));
        response.getWriter().flush();
        response.getWriter().close();
    }
}
